Cellen 2

R basics III — functions & packages

Gavin Simpson

Aarhus University

2025-02-12

Functions

Functions

A function is

  1. a sequence of 1 or more instructions (lines of code)
  2. takes 0 or more arguments
  3. returns something (possibly nothing or NULL, may be invisibly)

seq(), length() etc are all functions

Arguments

Functions typically take arguments — options that determine detail of what is done

v <- runif(n = 5)

round(v, digits = 1)
## [1] 0.4 0.5 0.2 0.4 0.0

n is an argument to runif

digits is an argument to round

args(round)
## function (x, digits = 0, ...) 
## NULL

Arguments

Arguments can be matched by name or position

round(x = v, digits = 1)
## [1] 0.4 0.5 0.2 0.4 0.0
round(v, 1)
## [1] 0.4 0.5 0.2 0.4 0.0
round(digits = 1, x = v)
## [1] 0.4 0.5 0.2 0.4 0.0
round(1, v) # wrong! But not an error
## [1] 1 1 1 1 1

Don’t name the first argument but name everything else

Packages

R comes with a lot of functions

  • implement the language for programming
  • utilities
  • mathematical
  • basic & advanced statistical

But it’s not comprehensive

R packages extend R with new functions that implement new statistical methods, utilities, or even entirely new domain specific languages

R packages are user-written and work just like those provided with R

Packages

Packages are typically installed from CRAN

Comprehensive R Archive Network

Packages are installed on to a computer into a library

Install a packages using

install.packages("pkg_name")

Load a package each time you want to use it with

library("pkg_name")

(Other repos are available, like GitHub, esp for development versions)